#include <Wire.h>
// Wire library uses 7-bit addresses and automatically
// sets the r/w bit
static const uint8_t ADXL345 = 0x53;
static const uint8_t DATAX0 = 0x32;
static const uint8_t DATA_FORMAT = 0x31;
static const uint8_t BW_RATE = 0x2C;
static const uint8_t POWER_CTL = 0x2D;
static const uint8_t BIT_SELF_TEST = (1 << 7);
static const uint8_t BIT_RANGE_2G = 0x00;
static const uint8_t BIT_RANGE_4G = 0x01;
static const uint8_t BIT_RANGE_8G = 0x02;
static const uint8_t BIT_RANGE_16G = 0x03;
static const uint8_t BIT_FULL_RES = 0x08;
static const uint8_t BIT_MEASURE = 0x08;

void setup()
{
  Wire.begin();
  Serial.begin(9600);
  // Put the device in self-test mode
  uint8_t dfreg = BIT_SELF_TEST | BIT_FULL_RES | BIT_RANGE_16G;
  // because the POWER_CTL register immediately follows the
  // DATA_FORMAT register, we can cheat a little and simply
  // write the two bytes sequentially.
  uint8_t pcreg = BIT_MEASURE;
  Wire.beginTransmission(ADXL345);
  Wire.send(DATA_FORMAT);
  Wire.send(dfreg);
  Wire.send(pcreg);
  Wire.endTransmission();
}

void loop()
{
  int i;
  // Put the read address on the bus
  Wire.beginTransmission(ADXL345);
  Wire.send(DATAX0);
  Wire.endTransmission();
  // Request data starting with the X register
  Wire.beginTransmission(ADXL345);
  // 6 bytes gets us the LSB and MSB of the XYZ data
  Wire.requestFrom(ADXL345, (uint8_t)6);
  // store the data in a signed integer quantity
  int16_t acc[3];
  // pointer to use to store the data
  byte *p = (byte*)&(acc[0]);
  // wait for 2 bytes to be available
  while (Wire.available() < 6) {}
  for (int i = 0; i < 6; i++)
  {
    *p = Wire.receive();
    p++; // advance the pointer to the next 8 bits
  }
  Wire.endTransmission();
  Serial.print(acc[0]); // finally, print the quantities
  Serial.print(" ");
  Serial.print(acc[1]);
  Serial.print(" ");
  Serial.println(acc[2]);
  delay(10); // delay a bit to avoid flooding
}
